<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>使用Promise加载图片</title>
</head>
<body>
  <script>
    function loadImage(src) {
      const promise = new Promise((resolve, reject) => {
        const img = document.createElement('img')        
        img.onload = function () {
          resolve(img)
        }
        img.onerror = function () {
          const error = new Error(`图片加载失败，src为：${src}`)
          reject(error)
        }
        img.src = src
      })
      return promise
    }

    const url1 = 'https://element.eleme.cn/static/theme-index-blue.c38b733.png'
    const url2 = 'https://element.eleme.cn/static/theme-index-blue.c38b733.png'
    loadImage(url1).then(x => {
      document.body.appendChild(x)
      return loadImage(url2) // 使用promise解决回调地狱
    }).then(img2 => {
      console.log('图片2也加载成功了')
    }).catch(err => {
      console.error(err)
    })
  </script>
</body>
</html>